import configAll from "@/config/configAll";
import dayjs from 'dayjs'
import 'dayjs/locale/zh-cn'
dayjs.locale('zh-cn') // 设置全局为中文

// 日期格式化
export function parseTime(time, pattern) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time)
    } else if (typeof time === 'string') {
      time = time.replace(new RegExp(/-/gm), '/').replace('T', ' ').replace(new RegExp(/\.[\d]{3}/gm), '');
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}


// 电话号码脱敏
export function mobileDesensitize(mobile) {
  if (!mobile) return ''
  return mobile.replace(/(\d{3})\d*(\d{4})/, '$1****$2')
}

// 微信名脱敏
export function wxDesensitize(weixin) {
  if (!weixin) return ''
  if (weixin.length < 0) {
    return `${weixin.charAt(0)}*`
  }
  return `${weixin.charAt(0)}${Array(weixin.length - 2).fill('*').join('')}${weixin.charAt(-1)}`
}

export function isNotEmpty(data) {
  return data !== '' && data !== null && data !== undefined
}

// 格式化期望薪资范围
export function formatSalaryRange(min, max) {
  const ranges = []
  if (isNotEmpty(min)) {
    ranges.push(min)
  }
  if (isNotEmpty(max)) {
    ranges.push(max)
  }
  return ranges.join(' - ')
}

/**
 * 获取文件路径，环境不同base路径不同
 * @param path
 * @returns {string}
 */
export function getFilePath(path) {
  if (!path) return ''
  if (/^https?:\/\//.test(path)) {
    return path
  }
  return `${configAll.baseURL}${path}`
}
/**
 * 计算最新消息展示时间
 * @param lastTime
 * @returns {number}
 */
export function calcLastTime(lastTime) {
  if (!lastTime) return ''
  const lastDateTime = dayjs(lastTime * 1000)
  const today = dayjs()
  if (lastDateTime.isSame(today, 'day')) {
    return lastDateTime.format('HH:mm')
  }
  if (today.diff(lastDateTime, 'day') <= 7) {
    return lastDateTime.format('dddd')
  }
  return lastDateTime.format('YYYY-MM-DD')
}

export function showToast(msg) {
  uni.showToast({
    title: msg,
    icon: 'none',
    duration: 3000,
  })
}
